package com.hfut.manage.controller;

import com.hfut.manage.pojo.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;

@RestController
@RequestMapping("/back")
public class BackController {

    @GetMapping
    public Result backupMySQL(
            @RequestParam(required = false) Optional<String> username1,
            @RequestParam(required = false) Optional<String> password1,
            @RequestParam(required = false) Optional<String> dbName1,
            @RequestParam(required = false) Optional<String> outputPath1) {

        String username = username1.orElse("root");
        String password = password1.orElse("");
        String dbName = dbName1.orElse("mytlias");
        String outputPath = outputPath1.orElse("./db_backup.sql");

        String[] command = {
                "mysqldump",
                "-u" + username,
                "--password=" + password,
                dbName
        };

        try {
            File outputFile = new File(outputPath);
            Process process = Runtime.getRuntime().exec(command);
            FileOutputStream out = new FileOutputStream(outputFile);
            consumeStream(process.getInputStream(), out);
            consumeStream(process.getErrorStream(), System.err);

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                // 读取文件内容
                String content = new String(Files.readAllBytes(Paths.get(outputPath)), StandardCharsets.UTF_8);
                out.close();
                outputFile.delete();
                return Result.success(content);
            } else {
                out.close();
                outputFile.delete();
                return Result.error(exitCode,"备份异常");
            }
        } catch (IOException | InterruptedException e) {
            Thread.currentThread().interrupt();
            return Result.error(0,"备份异常: " + e.getMessage());
        }
    }


    private void consumeStream(InputStream input, OutputStream output) {
        new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (output instanceof PrintStream) {
                        ((PrintStream) output).println(line);
                    } else {
                        output.write((line + "\n").getBytes());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}